<template>
  <div class="admin-users-container">
    <!-- 卡片容器 -->
    <el-card class="user-management-card">
      <template #header>
        <div class="card-header">
          <h3>用户管理</h3>
          <el-button @click="showAddUserDialog" type="primary">添加用户</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名或邮箱..."
        style="max-width: 300px; margin-bottom: 20px;"
        clearable
      />

      <!-- 用户列表 -->
      <el-table :data="filteredUsers" border stripe>
        <el-table-column prop="username" label="用户名" sortable />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="用户类型">
          <template #default="{ row }">
            <el-select v-model="row.userType" placeholder="选择类型" @change="() => updateUserType(row)">
              <el-option label="普通用户" value="user" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="row.active ? 'success' : 'danger'">
              {{ row.active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button @click="toggleUserStatus(row)" size="small" type="warning">
              {{ row.active ? '禁用' : '启用' }}
            </el-button>
            <el-button @click="deleteUser(row.id)" size="small" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="addUserVisible" title="添加新用户">
      <el-form :model="newUser" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="newUser.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newUser.password" show-password />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="newUser.email" />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="newUser.userType" placeholder="请选择用户类型">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addUserVisible = false">取消</el-button>
        <el-button @click="addUser" type="primary">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [],
      searchQuery: '',
      addUserVisible: false,
      newUser: {
        username: '',
        password: '',
        email: '',
        userType: 'user'
      }
    };
  },
  computed: {
    filteredUsers() {
      if (!this.searchQuery) {
        return this.users;
      }
      const query = this.searchQuery.toLowerCase();
      return this.users.filter(user =>
        user.username.toLowerCase().includes(query) ||
        user.email.toLowerCase().includes(query)
      );
    }
  },
  created() {
    this.fetchUsers();
  },
  methods: {
    async fetchUsers() {
      try {
        const response = await fetch('http://localhost:8081/api/users/all');
        const data = await response.json();
        this.users = data;
      } catch (error) {
        console.error('获取用户列表失败:', error);
        alert('无法加载用户列表');
      }
    },
    async addUser() {
      try {
        const response = await fetch('http://localhost:8081/api/users/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.newUser)
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || '添加用户失败');
        }

        alert('用户添加成功');
        this.addUserVisible = false;
        this.newUser = {
          username: '',
          password: '',
          email: '',
          userType: 'user'
        };
        this.fetchUsers();
      } catch (error) {
        alert(error.message);
      }
    },
    showAddUserDialog() {
      this.addUserVisible = true;
    },
    async updateUserType(user) {
      try {
        await fetch(`http://localhost:8081/api/users/${user.id}/type`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ userType: user.userType })
        });
        alert('用户类型更新成功');
      } catch (error) {
        console.error('更新用户类型失败:', error);
        alert('更新用户类型失败');
      }
    },
    async toggleUserStatus(user) {
      try {
        await fetch(`http://localhost:8081/api/users/${user.id}/toggle`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ active: !user.active })
        });
        user.active = !user.active;
      } catch (error) {
        console.error('切换用户状态失败:', error);
        alert('切换用户状态失败');
      }
    },
    async deleteUser(userId) {
      console.log('Attempting to delete user with ID:', userId);
      try {
        const response = await fetch(`http://localhost:8081/api/users/${userId}`, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          const errorData = await response.json();
          console.error('Error response from server:', errorData);
          throw new Error(errorData.message || '删除用户失败');
        }

        console.log('User deleted successfully');
        alert('用户删除成功');
        this.fetchUsers();
      } catch (error) {
        console.error('Error deleting user:', error);
        alert(error.message);
      }
    }
  }
};
</script>

<style scoped>
.admin-users-container {
  padding: 40px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-management-card {
  max-width: 900px;
  margin: 0 auto;
}
</style>